package cn.itsource.pet.service.impl;

import cn.itsource.basic.domain.Point;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.service.impl.BaiduAiAuditServiceImpl;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.*;
import cn.itsource.order.domain.OrderPetAcquisition;
import cn.itsource.order.mapper.OrderPetAcquisitionMapper;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.pet.domain.Pet;
import cn.itsource.pet.domain.SearchMasterMsg;
import cn.itsource.pet.domain.SearchMasterMsgAuditLog;
import cn.itsource.pet.mapper.PetMapper;
import cn.itsource.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.itsource.pet.mapper.SearchMasterMsgMapper;
import cn.itsource.pet.query.SearchMasterMsgQuery;
import cn.itsource.pet.service.ISearchMasterMsgService;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
@Transactional
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BaiduAiAuditServiceImpl baiduAiAuditService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;


    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        //        id        -   自增长
        //        name      -   来自页面
        //        age       -   来自页面
        //        gender    -   来自页面
        //        coat_color-   来自页面
        //        resources -   来自页面
        //        pet_type  -   来自页面
        //        price     -   来自页面
        //        address   -   来自页面
        //        state     -   来自实体默认值 //0表示待审核或驳回， 1表示已审核待处理，2表示处理成功
        //        title     -   来自页面
        //        user_id   -   谁发布的寻主消息 = 用户 = 登录了才能发布
        //        shop_id   -   获取最近的门店的id

        //1.获取登录人id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findBylogininfoId(logininfo.getId());
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsg.setState(0);
        //2.将寻主消息添加到数据库- 如何审核失败 - 修改寻主消息重新审核【shop_id】
        searchMasterMsgMapper.add(searchMasterMsg);

        //3.百度AI智能审核
        Boolean aBoolean = baiduAiAuditService.textAudit(searchMasterMsg.getCoatColor() + searchMasterMsg.getName() + searchMasterMsg.getTitle());
        Boolean bBoolean = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());

        if (aBoolean && bBoolean) {//3.1.审核成功
            searchMasterMsg.setState(1);//待处理
            //a.修改状态：0 - 1
            List<Shop> shops = shopMapper.findAll();
            //用户的地址
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            //店铺到用户的地址50公里内最近的店铺
            Shop shop = DistanceUtils.getNearestShop(point, shops);
            if (shop == null) {
                //b2.没有找到店铺 - 放到寻主池
                searchMasterMsg.setState(3);
            } else {
                searchMasterMsg.setShopId(shop.getId());
                Employee mapper = employeeMapper.findById(shop.getId());
                //SmsUtils.sendSms(mapper.getPhone(),"为您接到新的订单，请到"+searchMasterMsg.getAddress()+"收取宠物");
                System.out.println("为您接到新的订单，请到" + searchMasterMsg.getAddress() + "收取宠物");
                //b1.找到最近的店铺 - 分配店铺【设置到shopId】 - 发送短信给店铺管理员，告诉他去接回宠物
                //b3.更新数据库
                //c.添加审核日志
                SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
                log.setMsgId(searchMasterMsg.getId());
                log.setState(1);
                log.setNote("发布成功");
                searchMasterMsgAuditLogMapper.add(log);
            }
            searchMasterMsgMapper.update(searchMasterMsg);
        } else {
            searchMasterMsg.setState(-1);
            searchMasterMsgMapper.update(searchMasterMsg);
            //SmsUtils.sendSms(user.getPhone(),"审核失败，请重新上传宠物信息");
            System.out.println("审核失败，请重新上传宠物信息");
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setState(0);
            log.setNote("发布失败");
            log.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLogMapper.add(log);
            //3.2.审核失败
            //a.发送短信给用户告诉他审核失败，修改寻主消息
            //b.添加审核失败日志
            return AjaxResult.me().setSuccess(false).setMessage("寻主消息发布失败");
        }
        return new AjaxResult();
    }

    @Override
    //待审核
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询登录人
        Logininfo logininfo = LoginContext.getLogininfo(request);
        //查询员工数据
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        //判断员工是否是平台管理员
        if(employee.getShopId() != null){ //店铺管理员
            query.setShopId(employee.getShopId());
        }
        //查询
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findBylogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(Map<String, String> map) {
        long msgId = Long.parseLong(map.get("msgId"));   //寻主详情信息
        long empId = Long.parseLong(map.get("handler"));   //接受人员
        String note = map.get("note");    //简介
        //接单检验是否存在此订单    获取订单
        OrderPetAcquisition order =orderPetAcquisitionMapper.findBymsgId(msgId);
        //存在    告知已存在
        if(order != null){
            throw new BusinessException("订单进行中，请勿重复接单");
        }
        //不存在，将宠物数据添加进宠物表    查询宠物数据
        SearchMasterMsg msg = searchMasterMsgMapper.findBymsgid();
        Pet pet = mas2pet(msg);
        petMapper.add(pet);
        //获取接单对象通知接宠物    生成订单
        OrderPetAcquisition petorder = shengchendingdan(msg,empId,pet);
        orderPetAcquisitionMapper.add(petorder);

        System.out.println("请到"+msg.getAddress()+"接宠物");
    }
    //生成订单
    private OrderPetAcquisition shengchendingdan(SearchMasterMsg msg,Long empId,Pet pet) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(msg.getName()+"收购订单");
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 1000*60*60*24*2));
        order.setState(0);//待处理
        order.setPrice(msg.getPrice());
        //        order.setPaytype(); //现金支付
        order.setPetId(pet.getId());
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    private Pet mas2pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setState(0);
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }


}
